package com.mijie.homi.ns.service;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mijie.homi.common.constant.HomiConstants;
import com.mijie.homi.common.constant.MCKey;
import com.mijie.homi.common.domain.session.Session;
import com.mijie.homi.common.domain.user.User;
import com.mijie.homi.ns.core.HomiServer;
import com.mijie.util.Helper;

@Service
public class SessionService {
	
	@Autowired
	private MemcacheService mcs;
	@Autowired
	private UserService userService;
	
	private Logger logger = Logger.getLogger(SessionService.class);
	
	public static int getServerType(){
		return HomiConstants.HOMI_SOCKET_SERVER;
	}
	
	
	public String createSession(User user,long sessionId,String os,String appVer){
		Session session  = new Session(Helper.genUUID(),sessionId);
		session.setCreateAt(new Date());
		session.setOs(os.trim());
		session.setAppVer(appVer.trim());
		session.setUserId(user.getId());
		mcs.set(MCKey.SESSION,session.getToken(), MCKey.SESSION_TIMEOUT, session);
		mcs.set(MCKey.TOKEN_BY_USERID,String.valueOf(user.getId()), MCKey.SESSION_TIMEOUT, session.getToken());
		HomiServer.INFO("login success:userId->"+user.getId()+",mina session id->"+sessionId);
		return session.getToken();
	}
	
	
	public Integer getUserIdByToken(String token){
		Session session = (Session) mcs.get(MCKey.SESSION,token);
		return session==null?null:session.getUserId();
	}
	
	public long getIoSessionIdByToken(String token){
		Session session = (Session) mcs.get(MCKey.SESSION,token);
		return session==null?0:session.getId();
	}
	
	public Session getSessionByToken(String token){
		return (Session) mcs.get(MCKey.SESSION,token);
	}
	
	public Session getSessionByUserId(int userId){
		String token = (String) mcs.get(MCKey.TOKEN_BY_USERID, String.valueOf(userId));
		return token==null?null:getSessionByToken(token);
	}
	
	public long getIoSessionIdByUserId(int userId){
		String token = mcs.getString(MCKey.TOKEN_BY_USERID,String.valueOf(userId));
		if(token==null) return 0;
		Session session = (Session) mcs.get(MCKey.SESSION,token);
		return session==null?0:session.getId();
	}
	
	
	public void keepAliveSession(String token){
		Session session = (Session) mcs.get(MCKey.SESSION,token);
		if(session!=null){
			mcs.set(MCKey.SESSION,token, MCKey.SESSION_TIMEOUT, session);
			mcs.set(MCKey.TOKEN_BY_USERID,String.valueOf(session.getUserId()), MCKey.SESSION_TIMEOUT, token);
		}else{
			logger.info("keepAliveSession fail due to token timeout,token: "+token);
		}
	}
}
